package com.xayy.core.config.websocket;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author plq
 */
@Slf4j
public class WsClient extends WebSocketClient {

    private boolean isClosed;

    public ScheduledExecutorService scheduleExec = new ScheduledThreadPoolExecutor(1,
            new BasicThreadFactory.Builder().namingPattern("ScheduledThreadPoolExecutor-pool-%d").daemon(true).build());


    public WsClient(URI serverUri) {
        super(serverUri);
        this.isClosed = false;
    }


    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        log.info("连接成功-----状态码："+serverHandshake.getHttpStatus());
        send("HeartBeat");
        /*开始心跳检测*/
        this.startHeartbeat();
    }

    @SneakyThrows
    @Override
    public void onMessage(String s) {
        log.info("收到消息-----"+s);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        // 连接关闭，停止心跳定时器
        this.stopHeartbeat();
        this.isClosed = true;

        log.info("客户端已关闭!");
        log.info("参数s：" + s);
        log.info("参数i：" + i);
        log.info("参数b：" + b);
        WsClient client = MsgRunner.client;
        try {
            log.info("开始尝试重新连接...");
            if(client != null){
                client.reconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("后端消息监听重连失败！");
            client.reconnect();
        }

    }

    @Override
    public void onError(Exception e) {
        log.info("onError" + e);
        /*发生异常，停止心跳定时器*/
        this.stopHeartbeat();
    }

    /**
     * 开始心跳检测
     */
    private void startHeartbeat() {

        Runnable task = () -> {
            if (!isClosed) {
                /*发送心跳消息*/
                log.info("发送心跳消息：{}","HeartBeat-health");
                send("HeartBeat-health");
            }
        };
        scheduleExec.scheduleAtFixedRate(task,30000L, 30000L, TimeUnit.MILLISECONDS);
    }
    /**
     * 停止心跳检测
     */
    private void stopHeartbeat() {
        if (this.scheduleExec != null) {
            this.scheduleExec.shutdown();
        }
    }
}

